package com.yfqy.app.modules.banner.serviceimpl;

import cn.hutool.core.bean.BeanUtil;
import com.yfqy.app.domain.entity.Banner;
import com.yfqy.app.domain.entity.ProductSpuImages;
import com.yfqy.app.domain.mapper.BannerMapper;
import com.yfqy.app.domain.mapper.ProductSkuMapper;
import com.yfqy.app.domain.mapper.ProductSpuImagesMapper;
import com.yfqy.app.domain.mapper.ProductSpuMapper;
import com.yfqy.app.enums.DefaultStatus;
import com.yfqy.app.enums.ErrorCode;
import com.yfqy.app.exception.BusinessException;
import com.yfqy.app.modules.banner.service.BannerService;
import com.yfqy.app.modules.banner.vo.BannerVO;
import com.yfqy.app.modules.product.vo.ProductSkuVO;
import com.yfqy.app.modules.product.vo.ProductSpuVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * Banner服务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class BannerServiceImpl implements BannerService {

    private final BannerMapper bannerMapper;
    private final ProductSpuMapper productSpuMapper;
    private final ProductSkuMapper productSkuMapper;
    private final ProductSpuImagesMapper productSpuImagesMapper;

    @Override
    public List<BannerVO> getAllBanners() {
        List<Banner> banners = bannerMapper.getAllBanners();

        if (CollectionUtils.isEmpty(banners)) {
            return Collections.emptyList();
        }

        return BeanUtil.copyToList(banners, BannerVO.class);
    }

    @Override
    public ProductSpuVO getSpuDetailByBanner(Long id) {
        Assert.notNull(id, "Banner ID cannot be null");
        Assert.isTrue(id > 0, "Banner ID must be positive");

        log.debug("Getting SPU detail for banner ID: {}", id);

        // 验证banner是否存在且有效
        Banner banner = getValidBanner(id);

        // 如果banner没有关联SPU，直接返回null
        if (banner.getSpuId() == null) {
            log.info("Banner ID: {} has no associated SPU", id);
            return null;
        }

        // 获取SPU详情
        ProductSpuVO productSpuVO = getValidProductSpu(banner.getSpuId());

        // 设置SKU列表
        setProductSkus(productSpuVO);

        // 设置图片列表
        setProductImages(productSpuVO);

        log.info("Successfully retrieved SPU detail for banner ID: {}", id);
        return productSpuVO;
    }

    /**
     * 获取有效的banner
     */
    private Banner getValidBanner(Long id) {
        return Optional.ofNullable(bannerMapper.selectByPrimaryKey(id))
                .filter(banner -> banner.getStatus() == DefaultStatus.VALID.getStatus())
                .orElseThrow(() -> {
                    log.warn("Banner not found or invalid with ID: {}", id);
                    return new BusinessException(ErrorCode.BANNER_NOT_EXIT);
                });
    }

    /**
     * 获取有效的SPU
     */
    private ProductSpuVO getValidProductSpu(Long spuId) {
        return Optional.ofNullable(productSpuMapper.selectSpuVOById(spuId))
                .orElseThrow(() -> {
                    log.warn("Product SPU not found or invalid with ID: {}", spuId);
                    return new BusinessException(ErrorCode.PRODUCT_NOT_EXIST_ERROR);
                });
    }

    /**
     * 设置商品SKU列表
     */
    private void setProductSkus(ProductSpuVO productSpuVO) {
        List<ProductSkuVO> skuList = productSkuMapper.selectSkuVOsBySpuId(productSpuVO.getId());
        productSpuVO.setProductSkus(CollectionUtils.isEmpty(skuList) ?
                Collections.emptyList() : skuList);
    }

    /**
     * 设置商品图片列表
     */
    private void setProductImages(ProductSpuVO productSpuVO) {
        ProductSpuImages spuImages = productSpuImagesMapper.selectByPrimaryKey(productSpuVO.getId());

        if (spuImages != null) {
            productSpuVO.setMainImageList(splitImages(spuImages.getMainImages()));
            productSpuVO.setDetailImageList(splitImages(spuImages.getDetailImages()));
        } else {
            productSpuVO.setMainImageList(Collections.emptyList());
            productSpuVO.setDetailImageList(Collections.emptyList());
            log.warn("No product images found for SPU ID: {}", productSpuVO.getId());
        }
    }

    /**
     * 分割图片字符串为列表
     */
    private List<String> splitImages(String images) {
        return Optional.ofNullable(images)
                .map(img -> img.split(",")).stream().flatMap(Arrays::stream)
                .filter(img -> !img.trim().isEmpty())
                .collect(Collectors.toList());
    }
}